$(function () {
	router = new Router({
		container: "#container",
		enterTimeout: 250,
		leaveTimeout: 250
	});			
	
	var index = {
		url: "/",
		className: "index",
		render: function () {
			return setTitle("阿宝-赚钱二维码"), template("tpl_empty", {})
		},
		bind: function () {
			$(document).unbind("scroll");
		}
	};
	var gift = {
		url: "/gift/:mealid/:cid",
		className: "gift",
		render: function () {
			var mealid=this.params.mealid;
			var cid=this.params.cid;
			return new Promise(function (resolve, reject){
				setTitle("礼包");
				ajaxGet("firework/meals/mealgifts.json",{id:mealid,cid:cid},function(data){
					resolve(template("tpl_gas_gift", data.data));
				});
	        });
			//return setTitle("礼包"), template("tpl_empty", {})
		},
		bind: function () {
			$(document).unbind("scroll");
		}
	};
	router.push(gift);
	var purchased = {
		url: "/purchased",
		className: "purchased",
		render: function () {
			return setTitle("已购买"), template("tpl_purchased", {})
		},
		bind: function () {
			$(document).unbind("scroll");
			var _this=this;
			//设置全屏
			var wh = $(window).height();
			$(this).css("min-height",wh);
			//分页查询已购买的套餐
			/*pullLoadData(this,'.weui-tab__panel','.weui-tab__panel .weui-panel__bd',"firework/meals/myorders.json","tpl_purchased_data",{},function(data){
				if(data.code==404 && data.count<1){
					$(_this).find(".empty_data").show();
				}
			});*/
			tabPullLoadData(_this, '#meal_tab .weui-navbar__item', 
			'#tab_panel_0 .weui-media-box_text', 
			base_url+"firework/meals/myorders.json",
			"tpl_purchased_data",
			{status:2},function(data,tabPageName,itemIndex){
				//console.log(data,tabPageName,itemIndex)
				if(data.code==404 && data.count==0){
					$(_this).find(".tab_content_tab_"+itemIndex).html($(_this).find("#empty_data").clone().attr("id","empty_"+itemIndex).show());
				}
			},"get","weui-bar__item_on");
		}
	};
	router.push(purchased);
	var docid;
	var giftcontent = {
		url: "/giftcontent/:id/:docid",
		className: "giftcontent",
		render: function () {
			var giftid=this.params.id;
			docid=this.params.docid;
			return new Promise(function (resolve, reject){
				//setTitle("礼包");
				ajaxGet("firework/meals/mealgiftcontent.json",{id:giftid},function(data){
					resolve(template("tpl_gas_gift_content", data.data));
				});
	        });
			//return setTitle("礼包"), template("tpl_empty", {})
		},
		bind: function () {
			$(document).unbind("scroll");
			var _this=this;
			//获取文档内容
			ajaxGet("firework/meals/addoccontent.json",{id:docid},function(data){
				setTitle(data.data.title);
				var content = $(data.data.content);
				$(_this).find("#content").html(content);
				var tbindex=-1;
				$("#content").children().each(function(ind,ele){
					if($(ele).is("h2")){
						tbindex++;
						$("#tab_nav").append("<li class='weui-flex__item'><a href='#tabc"+tbindex+"'>"+$(ele).html()+"</a></li>")
						$("#tab_content").append("<div id='tabc"+tbindex+"'></div>");
						$(ele).remove();
					}else{
						$("#tabc"+tbindex).append(ele);
					}
				});
				$("#tab_nav").on("click","a",function(){
					var id=$(this).attr("href");
					$(this).parent().addClass("cu").siblings().removeClass("cu");
					$(id).show().siblings().hide();
					return false;
				});
				$("#tab_nav a").eq(0).click();
			});
		}
	};
	router.push(giftcontent);
	
	
	var xianjin = {		
		url: "/xianjin",
		className: "xianjin",
		render: function () {
			return setTitle("领宝店赚现金"), template("tpl_xianjin", {nav:1})
		},
		bind: function () {							
			$(document).unbind("scroll");
			var _this = this;
			var actId = 0;
			var index2 = 0;
			var arr2 = [];				
			var swiperIndex = 0;
			var cityId = 0;
			var lat = '';
			var lon = '';			
			getDegree();
			function getDegree() { //获取经纬度
				Promise.all([getLocation(true), setJSAPI()]).then(function (value) {
					var v1 = value[0];	
					lat = v1.latitude;
					lon = v1.longitude;	
					$('.goes2').on('click', function(){																				
						go('/wechat/pages/dianshang.html?longitude='+ lat +'&latitude='+ lon );
					});		
				});
			}																			
			$('.free_get').on('click', function(){
				$('.mask2').show();
			});		
			$('.cancels2').on('click', function(){
				$('.mask2').hide();
			});					
			if (localStorage.getItem('baoInfo')) {
				localStorage.removeItem('baoInfo');
			}	
			loadActivity(_this, "领宝码", 1);				
			//获取cookie中的邀请者fuid
			var invite = getCookie("invite");
			if(invite && invite>0){
				$(_this).find("#btn_lingbaodian").attr("href","/wechat/pages/renlingtype/"+invite+".html");
			}					

			function loadActivity(_this, tbName,tbindex) {
				return new Promise(function(resolve, reject) {
					ajaxGet("firework/bonus/activity.json", {}, function(data) {						
						$(_this).find(".period").html(data.data.name);
						$(_this).find(".total_prize").html(data.data.jiangjin.sum);
						$(_this).find(".nums").html(data.data.jiangjin.countName);
						var active = data.data;						
						actId = active.id;				
						active.tbname = tbName;
						if(tbindex==1){
							active.levels=active.jiangjin.levels;
							active.thname1="奖项";
							active.thname2="奖金";
						}else{
							active.levels=active.butie.levels;
							active.thname1="嘉宾";
							active.thname2="补贴";
						}
						$(_this).find("#action").append(template("tpl_jiangxiang", active));						
						getRecord(actId);												
						resolve(active);
					});
				});
			}			
			//获奖记录
			function getRecord(id){
				$(_this).find('.no_text').hide();
				ajaxGet('firework/services/findwithbonus.json',{
					id: id
				},function(res){	
					arr2 = res.data;
					$(_this).find('.totals').html(res.money);																						
					$(_this).find('.data_lists').append(template('tpl_prize_datas',res))						
				},function(error){
					$(_this).find('.no_text').show();
				});
			}			
			//查看赚钱码
			$('.data_lists').delegate('.data_list', 'click', function(ev){					
				if (ev.target.parentNode.className === 'show_code') {					
					index2 = $(this).index();	
					localStorage.setItem('baoInfo', JSON.stringify(arr2[index2]));
					go('#/code_money');										
				}					
			});			
			
			//去提现
			$(_this).find('.total_income').on('click', function(){
				$(_this).find('.mask').show();
			});
			$(_this).find('.cancels').on('click', function(){
				$(_this).find('.mask').hide();
			});
			$(_this).find('.goes').on('click', function(){
				go('http://a.app.qq.com/o/simple.jsp?pkgname=com.mofing');
			});
		}
	};

	var code_money = {
		url: "/code_money",		
		className: "code_money",
		render: function () {														
			return setTitle("阿宝-赚钱二维码"), template("tpl_code_money", {});			
		},
		bind: function () {		
			showLoading();													
			var _this = this;
			fullDocument(_this);
			$('body,html').scrollTop(0);
			var baoInfo = JSON.parse(localStorage.getItem('baoInfo'));	
			var codeArr = [];	
			var swiperIndex = 0;								
			$(document).unbind("scroll");				
			ajaxGet('utils/qrcode/shopposter/'+ baoInfo.id +'.json', {}, function(data){
				if (data.code === 200) {
					$(_this).find('.remind').show();
					$(_this).find('.title3').html(baoInfo.title);
					$(_this).find('.swiper-wrapper').html(template('tpl_code_auto',data));
					codeArr = data.data;					
					new Swiper("#swiper-code", { 								
						initialSlide: 0,
						speed: 400,  																														
						preventLinksPropagation : true,					
						effect : 'coverflow',
						grabCursor: true,
						centeredSlides: true,
						slidesPerView: 1.3,											
						coverflowEffect: {
							rotate: 50,
							stretch: 10,
							depth: 100,
							modifier: 1,
							slideShadows : false,
						},																																
						loop : false,
						on: {
							slideChangeTransitionStart: function() {									
								swiperIndex = this.activeIndex;	
								if (swiperIndex === data.data.length) {
									swiperIndex = 0;
								}																											                   																																												                   																		
							},							            
						}
					});	
					hideLoading();														
				}					
			});	
			//下载高清打印版
			$('.downLoad').on('click', function(){						
				go('#/codes/'+ encodeURIComponent(codeArr[swiperIndex]));							
			});
			//返回
			$('.goBack').on('click', function(){	
				go('#/xianjin');							
			});							
		}
	};

	var ur = '';
	var codes = {
		url: "/codes/:url",		
		className: "codes",
		render: function () {			
			ur = decodeURIComponent(this.params.url);						
			return setTitle("阿宝-赚钱二维码"), template("tpl_codes", {});			
		},
		bind: function () {									
			$(document).unbind("scroll");
			var _this = this;
			fullDocument(_this);
			$('.code2').attr('src', ur);					
		}
	};
	
	var manages = {
		url: "/manages",
		className: "manages",
		render: function () {
			return setTitle("宝店管理"), template("tpl_manages", {nav:2})
		},
		bind: function () {
			var _this = this;
			var ind = 0;
			var arr = [];
			var str = '';
			var obj = {};
			var lat = '';
			var lon = '';			
			getDegree();
			function getDegree() { //获取经纬度
				Promise.all([getLocation(true), setJSAPI()]).then(function (value) {
					var v1 = value[0];	
					lat = v1.latitude;
					lon = v1.longitude;	
					$('.add_store').on('click', function(ev){	
						ev.stopPropagation();																			
						go('/wechat/pages/dianshang.html?longitude='+ lat +'&latitude='+ lon );
					});		
				});
			}
			$(document).unbind("scroll");
			$(_this).find('.no_data').hide();						
			ajaxGet('service/appmange/getapp.json', {}, function(data){						
				if(data.code === 200){					
					arr = data.data;					
					if(arr.length === 0){
						$(_this).find('.no_data').show();
						return;
					}										
					$(_this).find('.store_lists').append(template('tpl_manage_datas',data))
					$(".store_lists").on('click','.store_list>p',function(e){												
						ind = +e.currentTarget.id;						
						obj.id = arr[ind].id;
						obj.menu_config = arr[ind].menu_config;
						obj.face_path = arr[ind].face_path;
						obj.title = arr[ind].title;
						if(arr[ind].isshow === 1){ //审核通过才有管理
							localStorage.setItem('shopInfo',JSON.stringify(obj));
							go('#/store_manage');	
						}											
					})					
				}else if(data.code === 404){										
					$(_this).find('.no_data').show();
				}
			},function(error){
				$(_this).find('.no_data').show();
			})
		}
	};
	
	var store_manage = {
		url: "/store_manage",
		className: "store_manage",
		render: function () {
			return setTitle("店铺管理"), template("tpl_store_manage", {nav:2})
		},
		bind: function () {
			var _this = this;
			$(_this).find(".store_manage").hide();
			var shopInfo = {};			
			var str = '';
			$(document).unbind("scroll");
			shopInfo = JSON.parse(localStorage.getItem("shopInfo"));
			if(shopInfo){
				$(".top_img>img").attr('src',shopInfo.face_path);
				$(".top_name>h5").html(shopInfo.title);
				$(".tops").css('background','url('+ shopInfo.face_path +') no-repeat center');				
			}
			ajaxGet('service/appmange/getuserconfig.json', shopInfo, function(data){
				if(data.code === 200){
					$(_this).find(".store_manage").show();					
					$(_this).find('.open_lists').append(template('tpl_open_function',data));
				}
			})
			$(".store_manage").on('click',function(){
				go('http://a.app.qq.com/o/simple.jsp?pkgname=com.mofing');
			})					
		}
	};
	
	var spread = {
		url: "/spread",
		className: "spread",
		render: function () {
			return setTitle("推广"), template("tpl_spread", {nav:3})
		},
		bind: function () {
			var _this=this;
			$(document).unbind("scroll");	
			ajaxPost('utils/docs/articles/10109.json',{},function(data){				
				$(_this).find("#data_lists").html(template("tpl_doc_data",data));
			})
		}
	};
	var releasType = '0',releasId='';
	var store_spread = {
		url: "/store_spread/:type/:id",
		className: "store_spread",
		render: function () {
			releasType = Number(this.params.type)
			releasId   = this.params.id
			return setTitle("宝店推广"), template("tpl_store_spread", {nav:3})
		},
		bind: function () {
			var _this=this,storeInfo={},face_url='',md5_img='',data = [],selInfo={},cat_arr=[],shopArr= [];				
			$(document).unbind("scroll");
			//页面初始化的时候，加载分类
			ajaxGet('social-ads/adCampaign/getPromCate.json',{},function(res){
				$(_this).find("#type-sel").html(template("tpl_extend_detail",res));
				cat_arr = res.data
				if(alreadyInfo){
					$('#type-sel').val(alreadyInfo.cat_id)
				}
			})
			//判读是否通知过用户
			ajaxGet('social-ads/adCampaign/noticerule.json',{},function(res){
				
			})
			//ios还是安卓
			iosOrAndr()
			//类型获取
			var type = Number($.getUrlParam('type'))
			//根据类型进行推广
			spreadByType()
			var itemInfo = JSON.parse(localStorage.getItem('selInfo')) || {};
			if(releasType == 1 || releasType == 3){
				//var itemInfo = JSON.parse(localStorage.getItem('selInfo'));
				if(itemInfo.id){
					selInfo = {
						vid : itemInfo.shop_id || itemInfo.app_id,
						id  : itemInfo.id
					}
					$('#seleted').show()
					$('#face').attr('src',itemInfo.face_path)
					$('.goods-name').html(itemInfo.title)
					if(itemInfo.price){
						$('.price').html('￥:'+itemInfo.price)
					}
					if(itemInfo.created){
						$('.time').html(itemInfo.created)
					}					
				}				
			}
			$('.show-size').click(function(){
				$('.dailog').show()
			})
			$('.close-img').click(function(){
				$('.dailog').hide()
			})
			//微信中的图片上传
			$('.add-store').click(function(){
				uploadImages({
					count: 1,
					sourceType:['album', 'camera']
				},function(localId){
					storeInfo.localId = localId
					$('.before-up').hide();
					$('.upload-ok').show();
					$('#up-img').attr('src',localId)
				},function(data,localId){
					face_url = data.url
					md5_img  = data.md5
				})
			})
			var alreadyInfo = JSON.parse(localStorage.getItem('alreadyInfo')) || '';
			if(alreadyInfo){
				//$('#type-sel').val(alreadyInfo.cat_id),
				$('#titles').val(alreadyInfo.title)
				$('#type-cost').val(alreadyInfo.cost_type)
				$('#cost-price').val(alreadyInfo.cost_price)				
				$('.company2').html(Number(alreadyInfo.cost_price).toFixed(2))
				$('#budget').val(alreadyInfo.budget)
				$('.company1').html(Number(alreadyInfo.budget).toFixed(2))
				$('#start-time').val(alreadyInfo.start_time)
				$('#end-time').val(alreadyInfo.end_time)
				if(alreadyInfo.localId){
					$('.before-up').hide().siblings('.upload-ok').show()
					$('#up-img').attr('src',alreadyInfo.localId)
					face_url = alreadyInfo.face_url
					md5_img  = alreadyInfo.md5_img
				}

			}
			//位ios和安卓的输入框做处理
			function iosOrAndr(){				
				var u = navigator.userAgent;
			    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; // android终端
			    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // ios
			    if(isAndroid){
			        $('#budget').attr('type','tel')
			        $('#cost-price').attr('type','tel')
			    }		
			}
//			//点击继续发布
//			$('.fabu-btn').on('click','.fabu-btn',function(){
//				$('.success-dailog').hide()
//			})			
//			//点击返回
//			$(_this).on('click','.back-btn-fail',function(){
//				goback(-1)
//			})
			//点击选择商品按钮
			$('.link-to-select').click(function(){
				//跳到列表页
				go('#/store_list/'+releasType);
				//获取到已经填写的数据
				var info = {
					cat_id 	   : $('#type-sel').val(),
					title	   : $.trim($('#titles').val()),
					localId	   : $('#up-img').attr('src') || '',
					face_url   : face_url,
					md5_img    : md5_img,
					cost_type  : $('#type-cost').val(),
					cost_price : $.trim($('#cost-price').val()),
					budget 	   : $.trim($('#budget').val()),
					start_time : $('#start-time').val(),
					end_time   : $('#end-time').val()	
				}
				//对已填写的数据做保存
				localStorage.setItem('alreadyInfo',JSON.stringify(info))
			})
			//店铺列表的点击
			$(_this).on('click','.swiper-slide',function(){
				var avatarWarrp = $(this).find('.avatar-warrp'),
					has 		= 	avatarWarrp.hasClass('select');
				if(!has){
					//所选中的样式					
					avatarWarrp.addClass('select');
					$(this).siblings().find('.avatar-warrp').removeClass('select')				
					avatarWarrp.find('.bg-img').addClass('sel-bg')
					$(this).siblings().find('.bg-img').removeClass('sel-bg')
					//所选中的数据
					var index = $(this).index()
					storeInfo.id  = data[index].id
					storeInfo.vid = data[index].id
					storeInfo.shop_name = data[index].title
					console.log(storeInfo)
				}
			})

			//点击提交按钮
			$('.submit-btn').click(function(){
				//console.log(typeof Number(itemInfo.id))
				//console.log(typeof itemInfo.id)
				//获取表单信息
				localStorage.removeItem('alreadyInfo')
				var id = $('#type-sel').val(),source_from = 0;
				console.log(id)
				cat_arr.forEach(function(item){
					if(item.id === Number(id)){
						storeInfo.cat_name = item.tag_name
					}					
				})
				if(_Global_== 'wechat'){
					source_from = 2
				}else if(_Global_== 'web'){
					source_from = 0
				}else{
					source_from = 1
				}
				var info = {					
					cat_id 	     : $('#type-sel').val(),
					cate_name    : storeInfo.cat_name,
					shop_name    : storeInfo.shop_name || itemInfo.shop_name,
					title	     : $.trim($('#titles').val()),
					budget       : $('#budget').val(),
					spread_type  : releasType,
					face_path    : face_url || '',
					md5_url      : md5_img  || '123',
					cost_type    : $('#type-cost').val(),
					cost_price   : $.trim($('#cost-price').val()),
					start_time   : $('#start-time').val().replace('T', ' '),
					end_time     : $('#end-time').val().replace('T', ' '),
					source_from  : source_from
				}
				if(releasType == '2' ){
					info.vid = selInfo.id || storeInfo.id || ''
					info.spread_type = 2
				}
				if(releasType == '1' ){
					info.gid = selInfo.id || storeInfo.id || ''
					info.shop_id  = storeInfo.shop_id   || itemInfo.shop_id,
					info.spread_type = 1
				}
				if(releasType == '3' ){
					info.nid = selInfo.id || storeInfo.id || ''
					info.shop_id = storeInfo.shop_id   || itemInfo.shop_id,
					info.spread_type = 3
				}				
				if(releasType == '4' ){
					delete info.shop_name
					info.prom_link = $('#link').val()
					info.spread_type = 4
				}
				if(storeInfo.isBack === 1){
					info.is_back = storeInfo.isBack
					info.id   = storeInfo.ad_id 
				}
				console.log(info)
				//表单验证的结果
				var result = validateForm(info)
				//验证通过
				if(result.type){
					ajaxPost('social-ads/adCampaign/addMarketAd.json',info,function(res){
						//广告币余额不足
						if(res.data.release_status == 0){
							releasId = res.data.ad_id
							
							//$('.number-val').text(res.data.ad_money)
							$('.fail-dialog').show()
							$(_this).find(".fail-dialog").html(template("tpl_pay_fail",res.data));
							sessionStorage.setItem('subInfo',JSON.stringify(res.data))
						}
						//推广成功
						else{
							$('.success-dailog').show()						
							$(_this).find(".success-dailog").html(template("tpl_pay_ok",res.data));
							showInfoMsg('推广成功')							
						}
					},function(){
						showErrorMsg('推广失败')
					})
				}
				//验证失败
				else{
					showErrorMsg(result.msg)
				}
			})
			var ad_id = ''
			//根据类型，显示推广内容
			function spreadByType(){
				if(releasType == '2'){
					document.title = '宝店推广'
					$('.is-link').hide() 
					$('#select-box').hide()
					$('.slide-warrp').show()
					getShops()
				}else if(releasType == '1'){
					document.title = '商品推广'
					$('.is-link').hide() 
					$('.type-goods').show().siblings('.type-store').hide()
				}else if(releasType == '3'){
					document.title = '文章推广'
					$('.left').text('请选取你要推广的文章')
					$('.right').text('选择文章>')
					$('.is-link').hide() 
					$('.type-goods').show().siblings('.type-store').hide()
				}else{
					$('#select-box').hide()
					document.title = '链接推广'
				}
			}
			//获取店铺
			function getShops(){
				ajaxGet('social-ads/adCampaign/getapp.json',{},function(res){
					if(res.code === 200){
						if(!res.data.length){
							$('.no-shops').show()
							showErrorMsg("您还没有店铺");
							return
						}
						//模板渲染
						res.data[0].hasClass = true
						$(_this).find(".swiper-wrappe").html(template("tpl_shop_list",res));
						//默认获取第一条的数据
						shopArr = data = res.data
						storeInfo.id  = data[0].id
						storeInfo.vid = data[0].id
						storeInfo.shop_name = data[0].title
						//获取回填的数据
						if(releasId != 0){
							getBackInfo()
						}
						//初始化swiper
						var swiper = new Swiper('.swiper-container', {
					      slidesPerView: 4,
					      spaceBetween: 30,
					      freeMode: true
					    });
					}else{
						
					}
					
				})
			}

			$('#cost-price').on('input',function(){
				var val = $(this).val()
				val = /^\d+\.?\d{0,2}$/.test(val) ? val : val.substring(0,val.length-1)
				$('.company2').text(Number(val).toFixed(2))
			})
			$('#budget').on('input',function(){
				var val = $(this).val()
				val = /^\d+\.?\d{0,2}$/.test(val) ? val : val.substring(0,val.length-1)
				$('.company1').text(Number(val).toFixed(2))
			})
			//失败充值按钮的点击
			$(_this).on('click','.chongzhi-btn',function(){
				go('#/unpublished/'+releasId)
			})
			//失败返回的点击
			$(_this).on('click','.back-btn-fail',function(){
				$('.fail-dialog').hide()
			})
			//成功返回的点击
			$(_this).on('click','.fabu-btn',function(){
				goback(-1)
			})
			//成功返回的点击
			$(_this).on('click','.back-btn',function(){
				goback(-1)
			})
			//表单验证
			function validateForm(form){
				var result = {
					type : false,
					msg  : ''
				}
				if(!form.cat_id){
					result.msg = '请选择分类'
					return result
				}
				if(!form.vid && releasType == '2'){
					result.msg = '请选择宝店'
					return result
				}
				if(!form.gid && releasType == '1'){
					result.msg = '请选择商品'
					return result
				}
				if(!form.nid && releasType == '3'){
					result.msg = '请选择文章'
					return result
				}
				if(! /((http|https):\/\/([\w\-]+\.)+[\w\-]+(\/[\w\u4e00-\u9fa5\-\.\/?\@\%\!\&=\+\~\:\#\;\,]*)?)/.test(form.prom_link)
					&& releasType == '4'){
					result.msg = '请输入正确的url地址'
					return result
				}
				if(!form.title){
					result.msg = '请输入标题'
					return result
				}
				if(!form.budget){
					result.msg = '请输入推广预算'
					return result
				}
				if(!form.start_time){
					result.msg = '请输入开始时间'
					return result
				}
				if(!form.end_time){
					result.msg = '请输入结束时间'
					return result
				}
				if(form.start_time > form.end_time){
					result.msg = '结束时间不能早于开始时间'
					return result
				}
				if(nowDateTime >= form.end_time){
					result.msg = '结束时间应大于当前时间'
					return result
				}
				if(!form.cost_type){
					result.msg = '请选择资费方式'
					return result
				}
				if(!form.cost_price){
					result.msg = '请输入单价'
					return result
				}
				if(form.cost_price <= 0){
					result.msg = '请输入有效的单价'
					return result
				}
				if(Number(form.budget) <= Number(form.cost_price)){
					result.msg = '推广预算必须大于单价'
					return result
				}
				console.log(Date.parse(form.end_time))
				result.type = true
				return result
			}
			//用户二次提交，获取首次提交的信息
			if(releasId != 0){
				getBackInfo()
			}
			var nowDateTime = ''
			function getDateTime(){
				var nDate = new Date()
				var year   = nDate.getFullYear()
				var month  = nDate.getMonth() + 1
				var day    = nDate.getDate()
				var hour   = nDate.getHours()
				var minute = nDate.getMinutes()
				month  = month  < 10 ? '0' + month  : month
				day    = day    < 10 ? '0' + day    : day
				hour   = hour   < 10 ? '0' + hour   : hour
				minute = minute < 10 ? '0' + minute : minute
				nowDateTime = year + '-'+month+'-' + day+' '+hour+':'+minute
				console.log(nowDateTime)
				console.log(nowDateTime)
			}
			getDateTime()
			function getBackInfo(){
				ajaxGet('social-ads/adCampaign/showReleaseData.json',{
					ad_id 		: releasId,
					spread_type : releasType
				},function(res){
					var data = res.data[0]
					if(!alreadyInfo.cat_id){
						$('#type-sel').val(data.cat_id)		
					}
					if(!alreadyInfo.title){
						$('#titles').val(data.title)		
					}
					if(!alreadyInfo.budget){
						$('#budget').val(data.budget)
						$('.company1').html(data.budget.toFixed(2))
					}
					if(!alreadyInfo.cost_price){
						$('#cost-price').val(data.cost_price)
						$('.company2').html(data.cost_price.toFixed(2))
					}
					if(!alreadyInfo.cost_type){
						$('#type-cost').val(data.cost_type)	
						$('#type-cost').attr('disabled','disabled')
					}
					if(!alreadyInfo.start_time){
						$('#start-time').val(data.start_time)	
					}
					if(!alreadyInfo.end_time){
						$('#end-time').val(data.end_time)	
					}
													
					//将图片显示出来
					if(!itemInfo.face_url){
						$('.before-up').hide().siblings('.upload-ok').show()
						//提交给服务器的相对路径
						face_url = data.path
						md5_img  = data.md5_url
						//用作展示的绝对路径
						$('#up-img').attr('src',data.face_path)
					}
					//商品的情况
					if(data.spread_type == 1){
						$('#seleted').show()
						if(!itemInfo.id){
							$('#face').attr('src',data.prom_data.face_path)
							$('.goods-name').text(data.prom_data.title).next().text("￥"+data.prom_data.price)
							selInfo.id 		  = data.gid
							storeInfo.shop_id = data.vid
							storeInfo.shop_name = data.shop_name
						}
					}
					//店铺的情况
					if(data.spread_type == 2){
						selInfo.id = data.vid			
						storeInfo.shop_name = data.shop_name
						shopArr.forEach(function(item,index){		
							if(item.id == selInfo.id){	
								var $slide = $('.swiper-slide')
								$slide.find('.avatar-warrp').eq(0).removeClass('select')
								$slide.find('.bg-img').eq(0).removeClass('sel-bg')	
								$slide.find('.avatar-warrp').eq(index).addClass('select')
								$slide.find('.bg-img').eq(index).addClass('sel-bg')									
							}
						})
					}
					//文章的情况
					if(data.spread_type == 3){
						$('#seleted').show()
						if(!itemInfo.id){
							$('#face').attr('src',data.prom_data.face_path)
							$('.goods-name').text(data.prom_data.title).next().text(data.prom_data.created)
							selInfo.id 		  = data.nid
							storeInfo.shop_id = data.vid 
							storeInfo.shop_name = data.shop_name
						}
					}
					//链接的情况
					if(data.spread_type == 4){
						$('#link').val(data.redirect_uri)
					}
					storeInfo.isBack = 1
					storeInfo.ad_id = releasId
				})
			}
		}
	};
	
	//推广类型
	var select_type = {
		url: "/select_type",
		className: "select_type",
		render: function () {
			return setTitle("选择推广类型"), template("tpl_select_type", {nav:3})
		},
		bind: function () {
			$(document).unbind("scroll");
			$('#store').click(function(){
				go('#/store_spread/'+2+'/'+0);
				removeStorege()
			})
			$('#goods').click(function(){
				localStorage.removeItem('selInfo')
				removeStorege()
				go('#/store_spread/'+1+'/'+0);
			})
			$('#article').click(function(){
				localStorage.removeItem('selInfo')
				removeStorege()
				go('#/store_spread/'+3+'/'+0);
			})
			$('#links').click(function(){
				removeStorege()				
				go('#/store_spread/'+4+'/'+0);
			})
			function removeStorege(){
				localStorage.removeItem('alreadyInfo')
			}
			setTitle('发布广告')
		}
	};
	var unpublishId = ''
	var unpublished = {
		url: "/unpublished/:ad_id",
		className: "unpublished",
		render: function () {
			unpublishId = this.params.ad_id
			return setTitle("选择推广类型"), template("tpl_unpublished", {nav:3})				
		},
		bind: function () {
			$(document).unbind("scroll");
			$('.chongzhi-btn').click(function(){
				$('.recharge').show()
			})
			var _this = this
			//固定金额的点击
			$('.number-item').click(function(){
				$(this).addClass('active').siblings().removeClass('active')
				var num = Number($(this).attr('data-num'))
				$('.money-num').html(num.toFixed(2))
				$('.quantity').html(num)
				$('#custom-num').val(num)
			})
			//自定义金额的时候，取消调固定金额的class
			$('#custom-num').focus(function(){
				$('.number-item').removeClass('active')
			})
			//获取到自定义金额的数量
			$('#custom-num').on('input',function(){
				//value.replace(/^(0+)|[^\d]+/g,'')
				var value = $.trim($('#custom-num').val())
				var num = Number(value)
				if(!num){
					$('.money-num').html(0.00)
					$('.quantity').html(0)
				}else{
					$('.money-num').html(num.toFixed(2))
					$('.quantity').html(num)
				}				
			})
			//确认支付的点击
			$('.confirm').click(function(){	
				var payNum = Number($.trim($('.money-num').html()))
				if(payNum <= 0){
					showErrorMsg('请输入正确的数量')
					return
				}
				payOrder(0,'payment.adrecharge',payNum).then(function(res){
					//showInfoMsg('充值成功')
					changeStatus()
				}).then(function(){
					showErrorMsg('充值失败')
				});
			})
			
			//充值成功之后立即执行
			function changeStatus(){
				ajaxGet('social-ads/adCampaign/rechargeAdAccount.json',{
					ad_id : unpublishId
				},function(res){
					$("#success-dailog").show()
					var sub = JSON.parse(sessionStorage.getItem('subInfo'))
					$(_this).find(".success-dailog").html(template("tpl_pay_ok",sub));									
				},function(res){
					$("#fail-dialog").show()
					res.ad_money = res.data
					$(_this).find(".fail-dialog").html(template("tpl_pay_fail",res));
				})
			}
			//失败弹框返回的点击
			$(_this).on('click','.back-btn-fail',function(){
				$('.fail-dialog').hide()
			})
			//失败弹框充值的点击
			$(_this).on('click','.chongzhi-btn',function(){
				$('.fail-dialog').hide()
			})
			//成功弹框继续发布的点击
			$(_this).on('click','.fabu-btn',function(){
				goback(-2)
			})
			//成功弹框返回的点击
			$(_this).on('click','.back-btn',function(){
				goback(-2)
			})
			
		}
	};
	//未发布的列表
	var release_list = {
		url: "/release_list",
		className: "release_list",
		render: function () {
			return setTitle("选择推广类型"), template("tpl_release_list", {nav:3})
		},
		bind: function () {
			$(document).unbind("scroll");
			var _this = this,parents = $(this).parents('.release-item');
			$(_this).on('click','.again',function(){
				var type = $(this).parents('.release-item').attr('data-type'),
					id   = $(this).parents('.release-item').attr('data-id'),
					status = $(this).attr('data-status')
					if(status !== '1' && status !== '32' && status !== '33' && status !== '34'){
						localStorage.removeItem('selInfo')
						go('#/store_spread/'+type+'/'+id)	
					}
			})
//			$(_this).on('click','.show-detail',function(){				
//				var $parentEl = $(this).parents('.release-item'),
//					id 		  = $parentEl.attr('data-id');
//				var releasing = {
//					avatar 	  : $parentEl.attr('data-avatar'),
//					shop_name : $parentEl.attr('data-name'),
//					title 	  : $parentEl.attr('data-title'),
//					status 	  : $parentEl.attr('data-status')
//				}
//				console.log(releasing)
//				localStorage.setItem('releasing',JSON.stringify(releasing))
//				go('#/release_detail/'+id)
//			})

			$('#selected-type').change(function(){					
				$(".dropload-down").remove();
				killPullLoad()
				$('.release-list').find('.release-item').remove()
				pullLoadData(_this,'.release','.release .release-list','social-ads/adCampaign/promlist.json',
				'tpl_release_common',{
					release_status:0,
					spread_type   :$(this).val()
				},function(){
					
				})
			})
			//对列表进行分页
			pullLoadData(_this,'.release','.release .release-list','social-ads/adCampaign/promlist.json',
			'tpl_release_common',{
				release_status:0,
				spread_type   :'0'
			},function(){
				
			})			
			setTitle('未发布')
			
		}
	};
	var releasing = {
		url: "/releasing",
		className: "releasing",
		render: function () {
			return setTitle("选择推广类型"), template("tpl_releasing", {nav:3})
		},
		bind: function () {
			$(document).unbind("scroll");
			var _this = this;
			//点击每一条数据
			$(_this).on('click','.release-item',function(){
				var id = $(this).attr('data-id')
				var releasing = {
					avatar 	  : $(this).attr('data-avatar'),
					shop_name : $(this).attr('data-name'),
					title 	  : $(this).attr('data-title'),
				}
				localStorage.setItem('releasing',JSON.stringify(releasing))
				go('#/release_detail/'+id)
			})
			//条件筛选
			$('#select-type').change(function(){
				killPullLoad()
				$(".dropload-down").remove();
				$('.releasing-list').find('.release-item').remove()
				//对列表进行分页
				pullLoadData(_this,'.release','.release .releasing-list','social-ads/adCampaign/promlist.json',
				'tpl_release_common',{
					release_status:1,
					spread_type   :$(this).val()
				},function(){
					
				})
			})
			//对列表进行分页
			pullLoadData(_this,'.release','.release .releasing-list','social-ads/adCampaign/promlist.json',
			'tpl_release_common',{
				release_status:1,
				spread_type   :'0'
			},function(){
				
			})
			setTitle('发布中')
			
		}
	};
	//充值中心-已废除
	var recharge = {
		url: "/recharge",
		className: "recharge",
		render: function () {
			return setTitle("选择推广类型"), template("tpl_recharge", {nav:3})
		},
		bind: function () {
			$(document).unbind("scroll");
			var _this = this;
			$('.number-item').click(function(){
				$(this).addClass('active').siblings().removeClass('active')
				var num = $(this).attr('data-num')
				$('.money-num').html(num)
				$('.quantity').html(num)
				$('#custom-num').val(num)
			})
			
			$('#custom-num').focus(function(){
				$('.number-item').removeClass('active')
			})
			$('#custom-num').blur(function(){
				var num = $('#custom-num').val()
				$('.money-num').html(num)
				$('.quantity').html(num)
				
			})
	
			
		}
	};
	var ggid = 0;
	var release_detail = {
		url: "/release_detail/:id",
		className: "release_detail",
		render: function () {
			ggid = this.params.id
			return setTitle("选择推广类型"), template("tpl_release_detail", {nav:3})
		},
		bind: function () {
			$(document).unbind("scroll");
			var _this = this,
				flag  = false,
				releasingInfo = JSON.parse(localStorage.getItem('releasing')) || {};
			$('.avatar-img').attr('src',releasingInfo.avatar)	
			$('.name').text(releasingInfo.title)	
			$('.desc').text(releasingInfo.shop_name)	
			if(releasingInfo.status == '4'){
				$('.status-text').text('已停止').parent().next().hide()
			}
			var nowTime = ''
			function getNowTime(){
				var oDate = new Date()
				var hour   = oDate.getHours()
				var minute = oDate.getMinutes()
				hour   = hour   < 10 ? '0'+hour   : hour
				minute = minute < 10 ? '0'+minute : minute
				nowTime = hour+':'+minute
			}
			
			getDetailInfo()
			setTitle('发布详情')
			//切换开始时间
			$('#start-time').change(function(){
				getNowTime()
				var startTime = $('#start-time').val(),
					endTime   = $('#end-time').val()
				//对开始和结束时间判断	
				if((startTime > endTime) || (startTime == endTime)){
					showErrorMsg('开始时间应早于结束时间')
					return
				}
				//如果有结束时间，向服务器请求
				if(endTime){
					getDetailInfo(startTime,endTime+' '+nowTime)
				}
			})
			//切换结束时间
			$('#end-time').change(function(){
				getNowTime()
				var startTime = $('#start-time').val(),
					endTime   = $('#end-time').val()
				if((startTime > endTime) || (startTime == endTime)){
					showErrorMsg('开始时间应早于结束时间')
					return
				}
				if(startTime){
					getDetailInfo(startTime,endTime+' '+nowTime)
				}
			})
			//点击暂停投放按钮
			$('.handle-btn').click(function(){
				$('#iosDialog1').fadeIn();

			})
			//点击弹框取消按钮
			$('#cancel').click(function(){
				$('#iosDialog1').fadeOut();
			})
			//点击弹框确定按钮
			$('#confirm').click(function(){
				ajaxGet('social-ads/adCampaign/pauseProm.json',{
					ad_id	   : ggid,
				},function(res){
					//停止投放成功
					$('.status-text').text('已停止').parent().next().hide()
					$('#iosDialog1').fadeOut();
				})
			})
			//点击问号
			$(_this).on('click','.help-img',function(){
				var str = $(this).attr('data-tip')
				getTip(str,3000)
			})
			//请求详情的数据
			function getDetailInfo(startTime,endTime){
				showLoading();
				ajaxGet('social-ads/adCampaign/promCount.json',{
					ad_id	   : ggid,
					start_time : startTime || '',
					end_time   : endTime   || ''
				},function(res){
					hideLoading();
					//首次进来加载数据中的时间
					if(!flag){
						$('#start-time').val(res.data.start_time)
						$('#end-time').val(res.data.end_time)
						flag = true
					}
					//对点击率做处理
					res.data.per = (res.data.click_per*100).toFixed(1)
					$(_this).find(".info-warrp").html(template("tpl_release_detail_info",res.data));
				})
			}
			//点击问号时的弹框
			function getTip(str,time){
				$('.detail').text(str).fadeIn()
				setTimeout(function(){
					$('.detail').fadeOut()
				},time)
			}
							
		}
	};
	//商品选择
	var select_store = {
		url: "/select_store",
		className: "select_store",
		render: function () {
			return setTitle("选择推广类型"), template("tpl_select_store", {nav:3})
		},
		bind: function () {
			$(document).unbind("scroll");
			
			var _this = this;
			//初始化滑动菜单
//			var swiper = new Swiper('.swiper-container', {
//		      slidesPerView: 5,
//		      spaceBetween: 30,
//		      freeMode: true
//		    });
//		    var type = Number($.getUrlParam('type')) - 1;
//		    //点击菜单
//		    $(_this).on('click','.swiper-slide',function(){
//		    	$(this).addClass('active').siblings().removeClass('active')
//		    	var typeId = $(this).attr('data')
//		    	getDataList(typeId)
//		    })
//		    //进行下拉菜单选择
//		    var shopid = '',seletedInfo = {},goodsArr = [];
//		    $('#shops').change(function(){
//		    	shopid = $(this).val()
//		    	getMenusList(shopid)
//		    })
//		    $(_this).on('click','.list-item',function(){
//		    	var index = $(this).index()
//		    	seletedInfo = goodsArr[index]
//		    	localStorage.setItem('selInfo',JSON.stringify(seletedInfo))
//		    	goback(-1)
//		    })
//		    //页面初始化加载下拉菜单列表
//		    ajaxGet('social-ads/adCampaign/getapp.json',{},function(res){
//		    	var optins = []
//		    	res.data.forEach(function(item){
//		    		item.tag_name = item.title
//		    	})
//		    	$(_this).find("#shops").html(template("tpl_extend_detail",res));
//		    	getMenusList(res.data[0].shop_id)
//		    })
//		    function getMenusList(id){
//		    	var info = {
//		   			flag_id : type,
//		   			shop_id : id
//		   		}
//		   		ajaxGet('social-ads/adCampaign/getAppCate.json',info,function(res){
//		   			res.data.forEach(function(item){
//		   				if(!item.cat_name){
//		   					item.cat_name = item.title
//		   				}		   				
//		   			})
//	   				$(_this).find(".swiper-wrapper").html(template("tpl_menus",res));
//	   				//swiper.update()
//	   				$('.swiper-wrapper').find('.swiper-slide').first().addClass('active')
//	   				getDataList(res.data[0].id)
//	   				var swiper = new Swiper('.swiper-container', {
//				      slidesPerView: 5,
//				      spaceBetween: 30,
//				      freeMode: true
//				    });
//		   		},function(){
//		   			showErrorMsg("该店铺暂时还没有数据");
//		   		})
//		    }
//		   	function getDataList(id){
//		   		var info = {
//		   			flag_id : type,
//		   			shop_id : shopid,
//		   			cat_id  : id
//		   		}
//		   		ajaxGet('social-ads/adCampaign/getProm.json',info,function(res){
//					goodsArr = res.data
//		   			$('.no-data').hide() && $('.list-warrp').show()
//		   			$(_this).find(".list-warrp").html(template("tpl_goods_list",res));
//		   			//为文章时没有价格
//		   			if(type == 2){
//				    	$('.price').hide()
//				    }			   			
//		   		},function(){
//		   			$('.list-warrp').hide()
//		   			$('.no-data').show()
//		   		})
//		   	}
		}
	};
	//店铺列表
	var storeType = '0'
	var store_list = {
		url: "/store_list/:type",
		className: "store_list",
		render: function () {
			storeType = this.params.type
			return setTitle("宝店"), template("tpl_store_list", {nav:3})
		},
		bind: function () {
			var _this = this,data = [];
			$(document).unbind("scroll");
			var type = $.getUrlParam('type')

			ajaxGet('social-ads/adCampaign/getapp.json',{},function(res){
				$(_this).find(".store-list").html(template("tpl_store_item",res));
				if(storeType == '1'){
					$('.sel-btn').html('选择商品')
				}else{
					$('.sel-btn').html('选择文章')
				}
			},function(){
				$('.no-shop').show()				
			})
			$(_this).on('click','.store-item',function(){
				var id = $(this).attr('data')
				var name = $(this).attr('data-name')
				if(storeType == '1'){					
					go('#/goods_select/'+id+'/'+storeType);
				}else{
					go('#/article_list/'+id+'/'+storeType);
				}
			})
		}
	};
	//商品列表
	var goodsParams = {}
	var goods_select = {
		url: "/goods_select/:id/:type",
		className: "goods_select",
		render: function () {
			goodsParams = this.params
			return setTitle("宝店"), template("tpl_goods_select", {nav:3})
		},
		bind: function () {
			var _this = this,data = [],info={
				shop_id : goodsParams.id,
				flag_id : 1
			};
			$(document).unbind("scroll");
			var type = '3'
			//获取菜单
			ajaxGet('social-ads/adCampaign/getAppCate.json',info,function(res){
				//数据处理
				res.data.forEach(function(item){
					if(!item.cat_name){
						item.cat_name = item.title
					}					
				})
				//模板渲染
				$(_this).find(".swiper-wrapper").html(template("tpl_menus",res));
				//给菜单第一个加选中样式
				$('.swiper-wrapper').find('.swiper-slide').first().addClass('active')
				//初始化滑动组件
				var swiper = new Swiper('.swiper-container', {
				      slidesPerView: 4,
				      spaceBetween: 30,
				      freeMode: true,
				      preventClicks : false
				    });
				//getGoodsList(res.data[0].id)    
				pullLoad(res.data[0].id)
			},function(){
				$('.not-class').show()
			})

			//var goodsList = []
			$(_this).on('click','.goods-item',function(){
				//var index = $(this).index(),
					var selInfo = {
						title 	  : $(this).attr('data-title'),
						price     : $(this).attr('data-price'),
						face_path : $(this).attr('data-face_path'),
						shop_name : $(this).attr('data-shop_name'),
						id : $(this).attr('data-id'),
					}
					selInfo.shop_id   = goodsParams.id  
					
					localStorage.setItem('selInfo',JSON.stringify(selInfo))
									
				goback(-2)
			})

			function pullLoad(id){
				tabPullLoadData(_this, '.swiper-container .swiper-slide', 
				'#goods-warrp', 
				base_url+"social-ads/adCampaign/getProm.json",
				"tpl_goods_selected",
				{cat_id:id,flag_id:1,shop_id:info.shop_id},function(){
					//console.log(data,tabPageName,itemIndex)
	//				if(data.code==404 && data.count==0){
	//					$(_this).find(".tab_content_tab_"+itemIndex).html($(_this).find("#empty_data").clone().attr("id","empty_"+itemIndex).show());
	//				}
				},"get","active",false,"tpl_no_goods");
			}
			setTitle('店铺列表')
		}
	};
	//文章列表
	var articleParams = {}
	var article_list = {
		url: "/article_list/:id/:type",
		className: "article_list",
		render: function () {
			articleParams = this.params
			return setTitle("宝店"), template("tpl_article_list", {nav:3})
		},
		bind: function () {
			var _this = this,data = [],info={
				shop_id : articleParams.id,
				flag_id : 2
			};
			$(document).unbind("scroll");
			var type = '3'
			//获取菜单
			ajaxGet('social-ads/adCampaign/getAppCate.json',info,function(res){
				//数据处理
				res.data.forEach(function(item){
					if(!item.cat_name){
						item.cat_name = item.title
					}					
				})
				//模板渲染
				$(_this).find(".swiper-wrapper").html(template("tpl_menus",res));
				//给菜单第一个加选中样式
				$('.swiper-wrapper').find('.swiper-slide').first().addClass('active')
				//初始化滑动组件
				var swiper = new Swiper('.swiper-container', {
				      slidesPerView: 4,
				      spaceBetween: 30,
				      freeMode: true
				    });
				pullLoad(res.data[0].id)
				//getGoodsList(res.data[0].id)    
			},function(){
				$('.not-class').show()
			})
			//列表的点击
			$(_this).on('click','.article-item',function(){
				var selInfo = {
					face_path : $(this).attr('data-face_path'),
					created   : $(this).attr('data-created'),
					title 	  : $(this).attr('data-title'),
					id 	      : $(this).attr('data-id'),
					shop_name : $(this).attr('data-name'),
				}
				selInfo.shop_id   = articleParams.id
				localStorage.setItem('selInfo',JSON.stringify(selInfo))					
				goback(-2)
			})
			//上拉加载更多
			function pullLoad(id){
				tabPullLoadData(_this, '.swiper-container .swiper-slide', 
				'.article-warrp', 
				base_url+"social-ads/adCampaign/getProm.json",
				"tpl_article_select",
				{cat_id:id,flag_id:2,shop_id:info.shop_id},function(){
					//console.log(data,tabPageName,itemIndex)
	//				if(data.code==404 && data.count==0){
	//					$(_this).find(".tab_content_tab_"+itemIndex).html($(_this).find("#empty_data").clone().attr("id","empty_"+itemIndex).show());
	//				}
				},"get","active",false,"tpl_no_article");


			}
		}
	};
	
	var quanming = {
		url: "/quanming",
		className: "quanming",
		render: function () {
			return setTitle("阿宝一起赚"), template("tpl_quanming", {nav:4})
		},
		bind: function () {
			$(document).unbind("scroll");			
			var _this=this;		
			var classArr = [];
			var dataArr = [];
			var str1 = '';			
			var classIndex = 0;
			var classId = 0;
			var page = 1;
			var pageSize = 50;
			var urls = '';							
			$.ajax({
				type: 'GET',
				url: 'https://market.mofing.com/usersnote/noteonlook/19740.json',
				dataType: 'json',
				data: {
					uid: login_uid,
					token: login_token
				},
				success: function(data){
					if(data.status === 200){						
						classArr = data.data;						
						classId = +classArr[classIndex].id;																													
						for(var i=0;i<classArr.length;i++){
							if(classIndex === i){
								str1 += '<div class="class_list sel" id="'+ i +'">'+ classArr[i].name +'</div>';	
							}else{
								str1 += '<div class="class_list" id="'+ i +'">'+ classArr[i].name +'</div>';
							}
						}
						$(_this).find(".class_lists").append(str1);
						if(classId!==0){
							getData();
						}
					}
				}
			})
			function getData(){
				dataArr = [];
				$(_this).find('.no_text').hide();
				$.ajax({
					type: 'GET',
					url: 'https://market.mofing.com/usersnote/notesbyonlook/'+ classId +'/zh/0/0/0/limit:'+ pageSize +'/page:'+ page +'.json',
					dataType: 'json',
					data: {
						order: 'news',
						uid: login_uid,
						token: login_token,
						ismyfriend: 0,
						ismine: 0
					},
					success: function(res){
						if(res.status === 200){														
							dataArr = res.data;	
							$(_this).find("#data_lists").html(template("tpl_quanming_data",res))
							$(_this).find(".no_text").hide();							
						}else if(res.status === 404){							
							$(_this).find(".no_text").show();
						}
					}
				})	
			}
			function format_month(val){		
				if(!val){
					return '--';
				}
				return +val.split(' ')[0].split('-')[1];
			}
			function format_day(val){
				if(!val){
					return '--';
				}
				return +val.split(' ')[0].split('-')[2];
			}			
			$(".class_lists").on('click','.class_list',function(e){		
				$(_this).find(".data_lists").html('');				
				$(this).siblings().removeClass('sel');
				$(this).addClass('sel');
				classIndex = +e.target.id;	
				classId = classArr[classIndex].id;	
				dataArr = [];
				getData();
			})
						
			
		}
	};
	
	var gas_selcid=0;
	var gas = {
		url: "/gasdesc/:id",
		className: "gas",
		render: function () {
			gas_selcid=this.params.id;
			return setTitle("开奖宝店券"), template("tpl_gas", {})
		},
		bind: function () {
			$(document).unbind("scroll");
			/*tuiguangquanShare().then(function(){
				console.log("获取分享物资完成")
				setJSAPI().then(function() {
					console.log("注册授权完成")
				})
			})*/
			var self = this;
			//加油站数据
			function getData(){
				//加油站信息
				ajaxPost("firework/meals/index.json",{withdoc:1},function(data){
					if(data.code === 200){
						var baobei_top=0;
						$(".summary .swiper-wrapper").html(template("tpl_gas_swiper", data));
						var numbers={};
						var prices={};
						var mealids={};
						$(data.data).each(function(ind,ele){
							numbers[ind]=1;
							prices[ind]=ele.price;
							mealids[ind]=ele.id;
						});
						var isFixed=false;
						//swiper参数列表
						var swiper=new Swiper("#gas_swiper", {
							autoHeight: true,
							initialSlide :gas_selcid,
							pagination: {
								el: ".weui-navbar",
								type: "bullets",
								clickable: !0,
								bulletClass: "weui-navbar__item",
								bulletActiveClass: "weui-bar__item_on",
								renderBullet: function(e, i) {
									var info=data.data[e];
									return '<div class="' + i + '">' + info.title+ "</div>"
								}
							},
							on: {
								init: function(){
								 	calculateTotal(numbers[this.activeIndex],prices[this.activeIndex]);
								},
								slideChange: function() {
								},slideChangeTransitionStart: function () {
									if(!isFixed){
										scrollTop3(baobei_top+1)
									}
								},
								slideChangeTransitionEnd: function () {
									numb=numbers[this.activeIndex];
									calculateTotal(numbers[this.activeIndex],prices[this.activeIndex]);
								}
							}
						});
						var maxNumber=99;
						var numb=1;
						//减少
						$(self).find(".minus").click(function(){
							if(numb<2){
								numb=1;
							}else{
								numb--;
							}
							setNumber($(this).parent().find(".snumber"));
						});
						//增加
						$(self).find(".add").click(function(){
							if(numb>=maxNumber){
								numb=maxNumber;
							}else{
								numb++;
							}
							setNumber($(this).parent().find(".snumber"));
						});
						//输入框直接改变
						$(self).find(".snumber").on("input",function(){
							if($.trim($(this).val())==""){
								return false;
							}
							numb=parseInt($(this).val());
							if(numb >maxNumber){
								numb=maxNumber;
							}else if(numb<1){
								numb=1;
							}
							setNumber(this);
						}).on("blur",function(){
							if($(this).val()==""){
								$(this).val(1);
								numb=1;
								setNumber(this);
							}
						});
						//改变数量
						function setNumber(obj){
							numbers[swiper.activeIndex]=numb;
							$(obj).val(numb);
							var price=prices[swiper.activeIndex];
							//改变联动数量
							$(".swiper-slide-active .liandong").each(function(){
								if($(this).data("fixed")==2){
									$(this).html(($(this).data("jishu")*numb).toFixed(2));
								}else{
									$(this).html($(this).data("jishu")*numb);
								}
							});
							calculateTotal(numb,price);
						}
						//计算总价
						function calculateTotal(numb,price){
							$("#total_prices").html((numb*price).toFixed(2));
						}
						//购买按钮
						$(".payment .buttons").click(function(){
							var obje = {};
							obje.amount = numbers[swiper.activeIndex];
							obje.lottery_meal_id = mealids[swiper.activeIndex];
							//获取订单号
							ajaxPost('firework/meals/createOrder.json',obje,function(data2){
								//拿到订单号再调用支付接口，获取微信返回的参数
								if(data2.code === 200){
									payOrder(data2.data,'Firework.meal').then(function(data){
										go("#/order/"+data.payid+"/"+data.id)
									},function(){
										
									})
								}
							})
						});
						//绑定滑动事件，强制固定导航
						$(document).scroll(function () {
							var i = $(this).scrollTop();							
							if (i > baobei_top) {
								$(self).find("#gas_swiper .weui-navbar").addClass("fix");
								isFixed=true;
							} else {
								$(self).find("#gas_swiper .weui-navbar").removeClass("fix");
								isFixed=false;
							}
						})
					}
				})
			}
			getData();
		}
	};
	var order_id,pay_order_id;
	var pay_success = {
		url: "/order/:id/:oid",
		className: "pay_success",
		render: function () {
			pay_order_id=this.params.id;
			order_id=this.params.oid;
			return setTitle("使用套餐"), template("tpl_empty", {})
		},
		bind: function () {
			var _this=this;
			$(document).unbind("scroll");
			var wh = $(window).height();
			$(this).css("min-height",wh);
			var Num = '';//数量
			var Store = '';//选中的店名
			var StoreId = 0;//选中的店id
			var Period = '';//选中的期数
			var PeriodId = 0;//选中的期数id
			var Lottery_meal_id = 0;
			
			function loadOrderInfo(){
				return new Promise(function(resolve, reject) {
					//宝店开奖返现
					ajaxGet('firework/meals/plan.json',{
						id: order_id,pid:pay_order_id
					},function(data){
						if(data.code === 200){
							if(data.data.status==0){
								data.data["lasttimestr"]=shijiandian(data.data.lasttime);
							}
							$(_this).html(template("tpl_pay_success", data.data));
							Num=data.data.amount;
							resolve(data.data);
						}
					})
				});
			}
			//必须等待订单请求完成
			loadOrderInfo().then(function(orderinfo){
				if(orderinfo.status==0){
					//再次支付
					$(_this).find("#btn_pay").click(function(){
						payOrder(order_id,'Firework.meal').then(function(data){
							go("#/order/"+data.payid+"/"+data.id)
						},function(){
							
						})
					});
					//倒计时
					daojishi($(_this).find("#daojishi"),orderinfo.lasttime,function(){
						window.location.reload();
					});
					return false;
				}else if(orderinfo.status!=1){
					return false;
				}
				//1秒后自动搜索，
        		var search_timer;
				/*$(_this).find("#searchStore").on("input",function(){
					clearTimeout(search_timer);
					var inputV=$.trim($(this).val());
					search_timer = setTimeout(function() {
	                    if(inputV.length > 0){
	                    	searchShop(inputV);
	                    }
	                }, 3500);
				});*/
				//点击搜索按钮，强制搜索
				$(_this).find(".searchs").on('click','.Search',function($event){
					$event.stopPropagation();
					var inputV = $.trim($(".searchStore").val());
					if(inputV.length === 0){
						showErrorMsg('请输入宝店名称！');
						return false;
					}
					searchShop(inputV);
				});
				//备选店铺选择
				$(_this).find("#store_lists").on("click","li",function(){
					Store = $(this).find("p").html();
					StoreId = $(this).data('storeid');
					ShopId = $(this).data('shopid');
					$("#searchStore").val(Store);
					$("#store_lists").hide();
				});
				//彩票期数
				ajaxPost('firework/meals/lottery.json',{},function(data){
					if(data.code === 200){
						$("#actionlist").html(template("tpl_actionlist",data));
					}
				})
				//选择彩票期数
				$(_this).find("#actionlist").on("click","div",function(){
					$(this).addClass('sel');
					$(this).siblings().removeClass('sel');
					Period = $(this).data('name');
					PeriodId = $(this).data('id');
				})
				//提交
				$(_this).find(".submits").on('click',function(){
					$(_this).remove("#confirm");
					if(Store == ''){
						showErrorMsg('请选择宝店');
						return;
					}
					if(Period == ''){
						showErrorMsg('请选择期数');
						return;
					}
					var confirmHtml = template("tpl_confirm",{name:Store,day:Period,numb:Num});
					$(_this).append(confirmHtml);
					$(_this).find("#confirm").on("click",".ensures",function(){
						var obj = {};
						obj.lottery_action_id = +PeriodId;
						obj.store_id = +StoreId;
						obj.shop_id = +ShopId;
						obj.amount = Num;
						obj.order_id = order_id;
						obj.pay_id = pay_order_id;
						ajaxPost('firework/meals/lotterysubmit.json',obj,function(data){
							$(".mask").hide();
							showInfoMsg("提交成功");
							setTimeout(function(){
								goback(-1)
							},2000);
						},function(){
							$(".mask").hide();
							showErrorMsg("提交失败");
							setTimeout(function(){
								goback(-1)
							},2000);
						})
					}).on("click",function(){
						$(this).remove();
					})
				})
			});
		}
	};
	
	var open_prize = {
		url: "/gas",
		className: "open_prize",
		render: function () {
			return setTitle("开奖宝店券"), template("tpl_open_prize", {})
		},
		bind: function () {			
			var total = 0; //总价格
			var allData = []; //数据集合，主要是看数量
			var index = 0; //所选索引
			var str = ''; //拼接字符串
			$(document).unbind("scroll");
			//初始化swiper
			var swiper = new Swiper('#gas_swiper', {
				autoplay: { delay: 5000},
				pagination: {
			    	el: '.swiper-pagination',
			  	}
			});
			//加油站数据
			function getData(){
				ajaxPost('firework/meals/index.json',null,function(data){
					if(data.code === 200){
						allData = data.data;	
						$(".all_prize").html(template("tpl_open_prize_one",data));
						for(var i=0;i<data.data.length;i++){		
							allData[i].NUM = 0; //新加字段 ---- 数量
						}							
					}
				})
			}
			getData();
			//加
			$(".all_prize").on("click",".plus1",function(e){
				total = 0;
				index = +e.target.name;				
				var val = $(".num_"+index).val();
				$(".show_"+index).css('visibility','visible');
				if(!val){
					$(".num_"+index).val(1);
					allData[index].NUM = 1;
				}else{
					var val2 = $(".num_"+index).val();
					val2++;
					$(".num_"+index).val(val2);
					allData[index].NUM = val2;
				}								
				var p1 = 0;
				for(var i=0;i<allData.length;i++){					
					p1 += allData[i].price*allData[i].NUM;					
				}
				total = p1.toFixed(2);
				$(".total").html(total);
			})
			//减
			$(".all_prize").on("click",".minus1",function(e){
				total = 0;
				index = +e.target.name;
				var val = $(".num_"+index).val();
				if(val > 1){
					var val2 = $(".num_"+index).val();
					val2--;
					$(".num_"+index).val(val2);					
					allData[index].NUM = val2;					
				}else{
					$(".num_"+index).val('');
					$(".show_"+index).css('visibility','hidden');					
					allData[index].NUM = 0;					
				}		
				var p1 = 0;
				for(var i=0;i<allData.length;i++){					
					p1 += allData[i].price*allData[i].NUM;					
				}
				total = p1.toFixed(2);	
				$(".total").html(total);;
			})
			//键盘输入
			$(".all_prize").bind("input propertychange",".num_"+index,function(){	
				total = 0;
				var val2 = +$(".num_"+index).val();
				$(".num_"+index).val(val2);				
				allData[index].NUM = val2;	
				var p1 = 0;
				for(var i=0;i<allData.length;i++){					
					p1 += allData[i].price*allData[i].NUM;					
				}
				total = p1.toFixed(2);
				$(".total").html(total);
 			})
			//支付
			$(".pay").on("click",function(){
				var arr = [];
				for(var i=0;i<allData.length;i++){
					if(allData[i].NUM > 0){
						var obj = {};
						obj.lottery_meal_id = allData[i].id;
						obj.amount = allData[i].NUM;
						arr.push(obj);
					}
				}
				if(arr.length === 0){
					alert('请选择购买数量！');
					return;
				}						
				//获取订单号（多订单）
				ajaxPost('firework/meals/createOrders.json',{
					data: arr
				},function(data2){
					//拿到订单号再调用支付接口，获取微信返回的参数
					if(data2.code === 200){
						payOrder(data2.data,'Firework.meal').then(function(data){
							showInfoMsg("支付成功！")
							//go("#/order/"+data.payid+"/"+data.id)
						},function(){
							
						})
					}
				})
			})
										
		}
	};

	router.push(index).push(xianjin).push(code_money).push(codes).push(manages).push(store_manage).push(spread).push(store_spread).push(select_type).push(select_store).push(store_list).push(goods_select).push(article_list).push(unpublished).push(release_list).push(release_detail).push(releasing).push(recharge).push(quanming).push(gas).push(pay_success).push(open_prize).setDefault("/").init();
});
function shangjiaShare() {
	 return new Promise(function(resolve, reject) {
		$.get(base_url + "wechat/pages/lingxianjin.json", function(data) {
			var e=data.data;
			console.log(e)
			wx.ready(function() {
				makeShare(e.title, e.desc, e.url, e.img);
				wx.hideMenuItems({
					menuList: ["menuItem:copyUrl", "menuItem:originPage", "menuItem:favorite", "menuItem:openWithQQBrowser", "menuItem:openWithSafari", "menuItem:share:email"]
				})
			});
			resolve(e);
		})
	});
}
function tuiguangquanShare() {
	 return new Promise(function(resolve, reject) {
		$.get(base_url + "wechat/pages/tuiguangquan.json", function(data) {
			var e=data.data;
			console.log(e)
			wx.ready(function() {
				makeShare(e.title, e.desc, e.url, e.img);
				wx.hideMenuItems({
					menuList: ["menuItem:copyUrl", "menuItem:originPage", "menuItem:favorite", "menuItem:openWithQQBrowser", "menuItem:openWithSafari", "menuItem:share:email"]
				})
			});
			resolve(e);
		})
	});
}


//支付倒计时
function daojishi(ele,time_left,callback){
	var stl=setInterval(function(){
		time_left--;
		if(time_left<1){
			clearInterval(stl);
			callback();
		}else{
			//格式化时分秒
			$(ele).html(shijiandian(time_left))
		}
	},1000);
}
//计算时间
function shijiandian(time_left){
	var tstr="";
	var tt=time_left;
	if(tt>3600){
		var hours=parseInt(tt/3600);
		if(hours<10){
			hours="0"+hours;
		}
		tstr+=hours+":";
		tt=tt-hours*3600;
	}
	if(tt>60){
		var minits=parseInt(tt/60);
		if(minits<10){
			minits="0"+minits;
		}
		tstr+=minits+":";
		tt=tt-minits*60;
	}
	if(tt<10){
		tt="0"+tt;
	}
	tstr+=tt;
	return tstr;
}
function searchShop(inputV){
	//宝店客搜索
	ajaxPost('firework/meals/search.json',{keyword: inputV},function(data){
		$("#store_lists").html(template("tpl_search_result",data)).show();
	},function(data){
		$("#store_lists").hide();
		showErrorMsg('该搜索内容暂无数据！');
	})
}
$(function(){
	//默认分享
	setJSAPI(10385).then(function(){
		console.log("默认分享初始化完成")
	})
})
